package com.reggie.service.facade.impl;

import com.reggie.common.enums.ResponseCode;
import com.reggie.common.exception.ReggieException;
import com.reggie.service.facade.FileSystemFacade;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;

/**
 * <p>
 * 文件系统服务实现类
 * </p>
 * 使用服务器本地存储
 *
 * @author yth
 * @since 2023-05-05-16:51
 */
@Slf4j
@Service
public class FileSystemFacadeImpl implements FileSystemFacade {

    @Value("${reggie.fss.file-base-path}")
    private String basePath;

    @Override
    public void getLocalImageFile(String fileName, OutputStream os) {
        try (FileInputStream fis = new FileInputStream(basePath + fileName)
        ) {
            // 写入文件数据
            byte[] bytes = new byte[1024];
            int len;
            while ((len = fis.read(bytes)) != -1) {
                os.write(bytes, 0, len);
                os.flush();
            }
        } catch (IOException e) {
            throw new ReggieException(ResponseCode.SERVER_ERROR, "下载文件失败");
        }
    }

    @Override
    public String saveImageFile(String originalFilename, InputStream is) {
        // 得到原文件后缀
        int index = originalFilename.lastIndexOf(".");
        String suffix = index != -1
                ? originalFilename.substring(index)
                : "";
        // 得到不重复的文件名
        String filename = UUID.randomUUID() + suffix;
        // 确保文件目录存在
        File dir = new File(basePath);
        if (!dir.exists() && !dir.mkdirs()) {
            throw new ReggieException(ResponseCode.SERVER_ERROR, "上传文件失败，文件目录不存在或无法创建");
        }
        // 转存文件
        try (OutputStream bos = new BufferedOutputStream(new FileOutputStream(basePath + filename))
        ) {
            byte[] bytes = new byte[1024];
            int len;
            while ((len = is.read(bytes)) != -1) {
                bos.write(bytes, 0, len);
                bos.flush();
            }
        } catch (IOException e) {
            log.error("上传文件时存储失败", e);
            throw new ReggieException(ResponseCode.SERVER_ERROR, "上传文件时存储失败", e);
        }
        return filename;
    }
}
